const errcode = require('../utils/errcode')
const utils = require('../utils')
const sqltool = require('sqltool')

exports.createPost = async ctx => {
  const {
    docId,
    tocId,
    title,
    abstract,
    content,
    contentType,
    tags
  } = ctx.request.body

  if (!title) return ctx.error(errcode.REQUIRED_PARAMS)

  const data = utils.pickBy({
    docId,
    tocId,
    title,
    abstract,
    content,
    contentType,
    tags
  })

  data.userId = ctx.state.loginId

  data.title = data.title.trim()

  const { insertId } = await ctx.models.post.create(data)

  ctx.success({
    id: insertId
  })
}


exports.updatePost = async ctx => {
  const {
    id,
    title,
    abstract,
    content,
    contentType,
    tags,
    status
  } = ctx.request.body

  if (!id) return ctx.error(errcode.REQUIRED_PARAMS)

  const data = utils.pickBy({
    title,
    abstract,
    content,
    contentType,
    tags,
    status
  })

  data.userId = ctx.state.loginId

  if (data.title) {
    data.title = data.title.trim()
  }

  const { affectedRows } = await ctx.models.post.update(data, { id: id })

  ctx.success({
    affectedRows: affectedRows
  })
}

exports.deletePost = async ctx => {
  const id = ctx.query.id

  if (!id) return ctx.error(errcode.REQUIRED_PARAMS)

  const { affectedRows } = await ctx.models.post.delete({ id: id })

  ctx.success({
    affectedRows: affectedRows
  })
}

exports.getPostInfo = async ctx => {
  const id = ctx.query.id
  const docId = ctx.query.docId
  const tocId = ctx.query.tocId

  const where = {}

  if (id) {
    where.id = id
  } else {
    where.docId = docId
    where.tocId = tocId
  }

  if (utils.isEmpty(where)) {
    return ctx.error(errcode.REQUIRED_PARAMS)
  }
  
  const data = await ctx.models.post.findOne({
    attrs: ['id', 'docId', 'tocId', 'title', 'abstract', 'content',
      'userId',
      'contentType', 'viewCount', 'tags', 'createdAt', 'updatedAt'],
    where: {
      status: 1,
      ...where
    }
  })

  if (data) {
    data.viewCount += 1
    await ctx.models.post.update({
      viewCount: data.viewCount
    }, { id: data.id })
  }

  ctx.success(data)
}
